<script setup name="billconfig">
import {
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI,
  GetMenuPermsAPI,
  GetMenuPermAPI,
  GetDelDataAPI,
  GetCodeRuleAPI,
} from '@/api/system/billconfig'
const tabs = ref('检验配置')
const { proxy } = getCurrentInstance()

const {
  sys_handover_method, //交接方式
  item_rank, // 送检阶别
  sys_inspection_type, // 检验类型
  sys_inspection_method, // 送检方式
  sys_control_items, // 管控项目
  sys_material_category, // 物料类别
  sys_ofcode_type,
} = proxy.useDict(
  'sys_handover_method',
  'sys_ofcode_type',
  'item_rank',
  'sys_inspection_type',
  'sys_inspection_method',
  'sys_control_items',
  'sys_material_category'
)

// 表单ref
const FormsRef = ref(null)

// 选中ID
const Ids = ref([])

// 是否禁用修改按钮
const Single = ref(false)

// 是否禁用删除按钮
const DelDisabled = ref(false)

// 列表数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 列表加载
const loading = ref(false)

// 保存按钮加载
const BtnLoading = ref(false)

// 信息展示状态
const Drawer = ref(false)

// 新增弹窗
const dialogVisible = ref(false)

// 单据选择弹窗
const BillIsShow = ref(false)

// 弹窗 标题
const title = ref('新增')

// 表格表单 数据
const TableForm = ref([])

// 勾选 表格表单
const formTebls = ref([])

// 表单ref
const ruleFormRef = ref()

// 编码规则下拉
const docTheRulesOpt = ref([])

// 按钮枚举
const buttonList = ref([])

// 状态 参数...
const state = reactive({
  loading: false, // 列表加载状态
  btnLoading: false, // 按钮加载状态
  isShow: false, // 弹窗状态
  summaryShow: false, // 需求汇总弹窗
  title: '新增', // 弹窗标题
  total: 0, // 列表总量
  ids: '', // 列表选择的id
})

// 列表枚举
const column = ref([
  {
    label: '配置编码',
    prop: 'docCode',
  },
  {
    label: '配置名称',
    prop: 'docName',
  },
  {
    label: '配置单据',
    prop: 'docConfigDict',
  },
  // {
  //   label: '交接方式',
  //   prop: 'docHandoverMethodDict',
  // },
  // {
  //   label: '超收标志',
  //   prop: 'docExcessMark',
  // },
  // {
  //   label: '超发标志',
  //   prop: 'docHairMark',
  // },
  // {
  //   label: '交接标志',
  //   prop: 'docHandoverMark',
  // },
  {
    label: '创建人',
    prop: 'createBy',
  },
  {
    label: '创建时间',
    prop: 'createTime',
  },

  {
    label: '操作',
    prop: 'x',
  },
])

// const anjianList = ref([])
// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  ofCodeType: '',
  ofCodeStr: '',
  ofCodeName: '',
  selectTime: '',
})

// 配置单据
const menuOptions = ref([])

/**
 * 查询枚举
 */
const SelectList = ref([
  { model: 'selectTime', type: '日期范围' },
  {
    label: '配置编码',
    model: 'docCode',
    type: '输入框',
    placeholder: '请输入配置编码',
  },
  {
    label: '配置名称',
    model: 'docName',
    type: '输入框',
    placeholder: '请输入配置名称',
  },
  {
    label: '配置单据',
    model: 'docConfigs',
    type: '层级下拉',
    placeholder: '请输入配置单据名称',
    config: {
      value: 'id',
      label: 'label',
      children: 'children',
    },
    opt: menuOptions,
  },
])

/**
 * 弹窗表单
 */
// 表单
const ruleForm = reactive({
  docCode: '', // 配置编码
  docName: '', // 配置名称
  docHandoverMethod: '', // 交换方式
  docConfig: '', // 配置单据
  docTheRules: '', // 编码规则
  docExcessMark: '2', // 超收标志 0为超收 1超收
  docHairMark: '2', // 超发标志 0为超收 1超收
  // docInspectionMark: '2', // 送检标志
  docHandoverMark: '2', // 交接标志
})

// 表格表单校验
const rules = reactive({
  docCode: [
    { required: true, message: '请填写配置编码', trigger: 'blur' },
    { validator: proxy.noChinese, trigger: 'blur' },
  ],
  docName: [{ required: true, message: '请填写配置名称', trigger: 'blur' }],
  docConfig: [{ required: true, message: '请填写配置单据', trigger: 'blur' }],
  docTheRules: [
    { required: true, message: '请选择编码规则', trigger: 'change' },
  ],
})

// 初始化按钮 原因：没有办法做到完全响应 每次事件触发再次执行
const initBtn = () => {
  buttonList.value = [
    { type: 'add', hasPermi: 'system:billconfig:add' },
    {
      type: 'remove',
      disabled: state.Single,
      hasPermi: 'system:billconfig:remove',
    },
  ]
}

// 勾选表格表单
const formTeblChange = (row) => {
  formTebls.value = row
}

// 码段添加
// const addTypeFn = () => {
//   if (tabs.value == '检验配置')
//     ruleForm.docConfigCode.check.push({
//       checkSubmit: null, // 送检阶别
//       checkType: null, // 送检类型
//       checkMode: null // 送检方式
//     })
//   if (tabs.value == '审核配置')
//     ruleForm.docConfigCode.audit.push({
//       auditControl: null, // 管控项目
//       auditTrigger: null, // 触发按键
//       auditMalType: null // 物料类别
//     })
// }

// 删除表格表单
const removeTypeFn = (scope) => {
  let arr = []
  if (tabs.value == '检验配置') arr = ruleForm.docConfigCode.check
  if (tabs.value == '审核配置') arr = ruleForm.docConfigCode.audit

  if (formTebls.value.length > 0) {
    formTebls.value.forEach((item) => {
      const Find = arr.findIndex((itemy) => item.docId == itemy.docId)
      arr.splice(Find, 1)
    })
  } else {
    arr.splice(arr.length - 1, 1)
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
// 勾选列表数据时
const handleSelectionChange = ({ row }) => {
  state.ids = row.map((t) => t.docId)
  state.rows = row
  console.log(row)

  state.multipleDis = !row.length
  state.Single = row.length != 1
  initBtn()
}
handleSelectionChange({ row: [] })

// 新增
const add = () => {
  getMenuPerm()
  billList()
  state.isShow = true
  state.title = '新增'
}

// 修改
const editDic = async (val) => {
  // debugger
  console.log(proxy.loading, 'proxy')

  // proxy.loading
  try {
    getMenuPerm()
    billList()
    const { data: res } = await GetDelDataAPI(val.docId)
    state.title = '修改'
    for (let Key in res.sysDocument) {
      ruleForm[Key] = res.sysDocument[Key]
    }
    // ruleForm.docConfig = res.docConfig
    state.isShow = true
    console.log(state.isShow, 'ruleForm.docConfig')
  } catch (err) {
    console.log(err)
  } finally {
    proxy.closeLoading()
  }
}

// 查看
const lookDic = async (val) => {
  console.log(proxy.loading, 'proxy')

  // proxy.loading()
  try {
    // getMenuPerm()
    billList()
    state.title = '查看'
    for (let Key in val) {
      ruleForm[Key] = val[Key]
    }
    ruleForm.docConfig = val.docConfig
    state.isShow = true
  } catch {
  } finally {
    proxy.closeLoading()
  }
}

// 新增提交
const addSubmit = async () => {
  BtnLoading.value = true
  try {
    const valid = await ruleFormRef.value.validate()
    if (!valid) return
    await AddDataAPI(ruleForm)
    proxy.successMsg('新增成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 修改保存
const editSubmit = async () => {
  BtnLoading.value = true
  try {
    const valid = await ruleFormRef.value.validate()
    console.log(valid, 'valid')
    if (!valid) return

    await EditDataAPI(ruleForm)
    proxy.successMsg('修改成功')
    close()
    getList()
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 删除
const del = async (val) => {
  await DelDataAPI(state.ids.length <= 0 ? val : state.ids.join(','))
  proxy.successMsg('删除成功')
  getList()
}
const remove = async (val) => {
  const result = await proxy.DelMessageBox('是否删除所选的数据?')
  if (!result) return
  await DelDataAPI(state.ids.length <= 0 ? val : state.ids.join(','))
  proxy.successMsg('删除成功')
  getList()
}
// 弹窗结束
const close = () => {
  state.isShow = false
  for (let KEY in ruleForm) {
    ruleForm[KEY] = ''
  }
  // ruleForm.docConfigCode = {
  //   check: [],
  //   audit: []
  // }
}

const docHandoverMarkChange = (val) => {
  if (val == 1) {
    rules.docHandoverMethod = [
      { required: true, message: '请选择交换方式', trigger: 'change' },
    ]
  } else {
    delete rules.docHandoverMethod
  }
}

// 选择单据
const nodeClick = async (val) => {
  ruleForm.docConfig = val[val.length - 1]
  // getAnjian(val[val.length - 1])
}

// 查询案件下拉列表
// const getAnjian = async id => {
//   const res = await GetMenuPermsAPI(id)
//   anjianList.value = res.data.map(item => ({
//     label: item.menuName,
//     value: item.menuId
//   }))
// }

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    state.total = res.total
    TableData.value = res.rows
  } catch (err) {
  } finally {
    loading.value = false
  }
}

// 查询按钮
const selectSubmit = (val) => {
  console.log(val, 'val')

  for (let KEY in val) {
    query[KEY] = val[KEY]
  }
  console.log(typeof query.bilds)

  query.docConfigStr =
    typeof query.bilds != 'string' ? query.bilds?.join(',') : ''
  getList()
}

/** 单据规则 查询列表 */
const billList = async () => {
  const res = await GetCodeRuleAPI()
  docTheRulesOpt.value = res.data
}

const getMenuPerm = async () => {
  const res = await GetMenuPermAPI()
  menuOptions.value = res.data
}
getMenuPerm()
getList()
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <p-select-form :selectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <!-- 按钮组件 -->
      <p-button :list="buttonList" @add="add" @remove="del" />
      <!-- 表格数据 -->
      <p-table
        keyId="purchaseOrderPlacementId"
        :loading="state.loading"
        :data="TableData"
        :column="column"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        :total="state.total"
        @change="handleSelectionChange"
        @pagination="getList"
      >
        <template #columnCell="{ column, record }">
          <div v-if="column.label == '超发标志'">
            <p-switch disabled v-model="record.docHairMark" />
          </div>
          <div v-if="column.label == '超收标志'">
            <p-switch disabled v-model="record.docExcessMark" />
          </div>
          <div v-if="column.label == '交接标志'">
            <p-switch disabled v-model="record.docHandoverMark" />
          </div>
          <div v-if="column.prop == 'x'">
            <p-operate
              :list="[
                {
                  icon: 'DeleteFilled',
                  emit: 'remove',

                  text: '删除',
                  type: 'danger',
                  hasPermi: 'normalMonthly:plan:remove',
                },
                {
                  icon: 'Edit',
                  emit: 'edit',

                  text: '修改',
                  type: 'primary',
                  hasPermi: 'system:billconfig:edit',
                },

                {
                  icon: 'Search',
                  emit: 'look',
                  disabled: false,
                  text: '查看',
                  type: 'primary',
                  hasPermi: 'system:billconfig:query',
                },
              ]"
              @records="records(record.docId)"
              @edit="editDic(record)"
              @remove="remove(record.docId)"
              @look="lookDic(record)"
              @revocation="revocation(record.purchaseOrderPlacementId)"
              @bacthArrival="bacthArrivalDic(record.purchaseOrderPlacementId)"
              @examine="eamineDic(record)"
            />
          </div>
        </template>
      </p-table>
    </el-card>
    <!-- 新增弹窗 -->
    <p-dialog
      width="50%"
      v-model="state.isShow"
      :title="state.title"
      @ok="state.title == '新增' ? addSubmit() : editSubmit()"
      @close="close"
    >
      <template #body>
        <el-form
          ref="ruleFormRef"
          :inline="true"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="配置编码" prop="docCode">
            <el-input
              clearable
              v-model="ruleForm.docCode"
              :disabled="state.title != '新增'"
              placeholder=" 请输入内容"
            />
          </el-form-item>
          <el-form-item label="配置名称" prop="docName">
            <el-input
              v-model="ruleForm.docName"
              :disabled="state.title == '查看'"
              clearable
              placeholder="请填写配置名称"
            />
          </el-form-item>
          <el-form-item label="配置单据" prop="docConfig">
            <el-cascader
              v-if="title == '新增'"
              v-model="ruleForm.docConfigs"
              :disabled="state.title == '查看'"
              :show-all-levels="false"
              :options="menuOptions"
              node-key="id"
              :props="{ label: 'label', value: 'id' }"
              @change="nodeClick"
            />
            <el-input v-else v-model="ruleForm.docConfigDict" disabled />
          </el-form-item>
          <!-- <el-form-item label="交接方式" prop="docHandoverMethod">
            <p-select
              :disabled="title == '查看'"
              v-model="ruleForm.docHandoverMethod"
              :option="sys_handover_method"
              placeholder="请选择交接方式"
            />
          </el-form-item> -->
          <el-form-item label="编码规则" prop="docTheRules">
            <p-select
              :disabled="state.title == '查看'"
              :option="docTheRulesOpt"
              v-model="ruleForm.docTheRules"
              clearable
              placeholder="请选择编码规则"
            />
          </el-form-item>
        </el-form>
        <!-- <div class="swBox">
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超收标志</label>
              <p-switch
                :disabled="title == '查看'"
                v-model="ruleForm.docExcessMark"
              />
            </div>
            <div class="flex-items-center" style="margin-left: 20px">
              <label for="超收标志">交接标志</label>
              <p-switch
                @change="docHandoverMarkChange"
                :disabled="title == '查看'"
                v-model="ruleForm.docHandoverMark"
              />
            </div>
          </div>
          <div class="switch flex-items-center">
            <div class="flex-items-center">
              <label for="超收标志">超发标志</label>
              <p-switch
                :disabled="title == '查看'"
                v-model="ruleForm.docHairMark"
              />
            </div>
          </div>
        </div> -->
      </template>
    </p-dialog>
  </div>
</template>
<style scoped lang="scss">
.caozuo {
  float: right;
  display: flex;
  margin-bottom: 10px;
  justify-content: space-evenly;
}

.Btn {
  margin-top: 20px;
  display: flex;
  float: right;
}

.switch {
  display: flex;
}

.app-container v-deep .el-form-item__content {
  width: 228px;
}

.Xiaoheforms {
  display: flex;
}

.swBox {
  margin-left: 20px;

  .switch {
    display: flex;
    align-items: center;

    label {
      display: inline-block;
      width: 60px;
    }
  }
}
</style>
